/* @flow */

import {
  warn,
  nextTick,
  emptyObject,
  handleError,
  defineReactive
} from '../util/index'

import { createElement } from '../vdom/create-element'
import { installRenderHelpers } from './render-helpers/index'
import { resolveSlots } from './render-helpers/resolve-slots'
import { normalizeScopedSlots } from '../vdom/helpers/normalize-scoped-slots'
import VNode, { createEmptyVNode } from '../vdom/vnode'

import { isUpdatingChildComponent } from './lifecycle'

export function initRender (vm: Component) {
  vm._vnode = null // the root of the child tree
  vm._staticTrees = null // v-once cached trees

  //提供给子类
  const options = vm.$options

  //得到当前组件的vnode
  const parentVnode = vm.$vnode = options._parentVnode 

  //上下文，其实就是当前组件的父级
  const renderContext = parentVnode && parentVnode.context

  //_renderChildren是在./init.js/initInternalComponent方法里面添加的属性，指向当前组件vnode的children
  //当前组件里面包含子标签时，_renderChildren才会不为空, 这里检查当前vnode是否存在slot
  //$slots = { defalut: [vnode,vnode,vnode] }
  vm.$slots = resolveSlots(options._renderChildren, renderContext)

  //一个冻结的空对象
  vm.$scopedSlots = emptyObject

  //这个函数很重要，就是用其来解析通过render 生成的render表达式函数
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)

  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)


  const parentData = parentVnode && parentVnode.data

  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
    }, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
    }, true)
  } else {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
  }
}

export let currentRenderingInstance: Component | null = null

// for testing only
export function setCurrentRenderingInstance (vm: Component) {
  currentRenderingInstance = vm
}



/**
 * 执行完renderMixin方法后，Vue将拥有的属性为
 * Vue.__proto__.$nextTick  = function
 * Vue.__proto__._render = function
 * Vue.__proto__.$vnode = undefined
 */
export function renderMixin (Vue: Class<Component>) {
  // install runtime convenience helpers
  installRenderHelpers(Vue.prototype)

  Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this)
  }

  //将platforms/web/entry-runtime-with-compiler.js对$mount方法增强时
  //挂载的render方法转为虚拟的VNode
  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options

    //首次初始化不存在,只有子组件才会存在此属性
    //当前保存的属性就是组件在父类里面的标签vnode
    //当前是组件才会走这路线
    //_parentVnode在create-component.js/createComponentInstanceForVnode挂载
    if (_parentVnode) {

      /**
       * 解析插槽属性
       * 这里如果是普通插操其实就是将vm.$slots的值都已函数的形式保存下来然后返回
       * 没有插槽属性时: vm.$scopedSlots = { $hasNormal: false, $key: undefined, $stable: true }
       */
      vm.$scopedSlots = normalizeScopedSlots(
        _parentVnode.data.scopedSlots, //默认传值插槽存放此处
        vm.$slots, //默认不传值插槽存放此处
        vm.$scopedSlots
      )
    }


    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
 
      //不需要维护堆栈，因为调用了所有的render fn
      //彼此分开。调用嵌套组件的render fn
      //修补父组件时。
      currentRenderingInstance = vm
      //render就是一个new Function返回的执行函数，
      //_renderProxy在init.js中的_init方法挂载，里面的值就是data属性，这里采用了with模块改变其作用域
      //$createElement在上面的代码initRender中挂载，实际是返回了createElement方法的调用结果
      //这里虽然传递了vm.$createElement方法但是在render初始化时里面没有调用到，就只调用了_c，
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {
        try {
          vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
        } catch (e) {
          handleError(e, vm, `renderError`)
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    } finally {
      currentRenderingInstance = null
    }

    // 目子只知道vm.$createElement里面生成Vnode,并且如果有子类会形成递归，暂时未知什么情况会返回数组
    if (Array.isArray(vnode) && vnode.length === 1) {
      vnode = vnode[0]
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
        warn(
          'Multiple root nodes returned from render function. Render function ' +
          'should return a single root node.',
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }
}
